<?php

namespace app\activity\controller;

use app\api\controller\Activity;
use app\api\controller\tools\LiteApp;
use library\Controller;
use think\Db;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;
use WePay\Refund;

/** 订单
 * Created by PhpStorm.
 * User: ycp
 * Date: 2019/11/18
 * Time: 21:07
 */

class Order extends Controller
{
    protected $table = 'lite_order';
    protected $activityTable = 'lite_activity';
    protected $groupTable = 'lite_activity_group';
    protected $packageTable = 'lite_activity_package';
    protected $memberTable = 'store_member';
    protected $orderInfoTable = 'lite_user_info';
    protected $couponsTable = 'lite_coupons';
    protected $couponsRecordTable = 'lite_coupons_record';

    //订单首页
    public function index()
    {
        $this->title = '订单管理';
        $where = ['is_deleted' => '0'];
        $this->statusTitle = ['0' => '未开始', '1' => '进行中', '2' => '已结束'];
        $this->_query($this->table)->like('name')->where($where)->order('id desc')->page();
    }

    /**
     * 订单列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _index_page_filter(array &$data)
    {

        $activityList = db($this->activityTable)->whereIn('id', array_unique(array_column($data, 'activity_id')))->select();
        $groupList = db($this->groupTable)->whereIn('id', array_unique(array_column($data, 'group_id')))->select();
        $packageList = db($this->packageTable)->whereIn('id', array_unique(array_column($data, 'package_id')))->select();


        $userIds = array_unique(array_column($data, 'user_id'));
        $memberList = db($this->memberTable)->whereIn('openid', $userIds)->select();
        $orderInfoList = db($this->orderInfoTable)->whereIn('lite_user_id', $userIds)->select();
        //

        foreach ($data as &$vo) {
            list($vo['member'], $vo['list']) = [[], [], []];
            foreach ($activityList as $activity) if ($activity['id'] === $vo['activity_id']) {
                $vo['activityInfo'] = $activity;
            }
            foreach ($groupList as $group) if ($group['id'] === $vo['group_id']) {
                $vo['groupInfo'] = $group;
            }
            foreach ($packageList as $package) if ($package['id'] === $vo['package_id']) {
                $vo['packageInfo'] = $package;
            }
            foreach ($memberList as $member) if ($member['openid'] === $vo['user_id']) {
                $member['nickname'] = urldecode(emoji_decode($member['nickname']));
                $vo['member'] = $member;
            }
            foreach ($orderInfoList as $orderInfo) if ($orderInfo['lite_user_id'] === $vo['user_id']) {
                $vo['info'] = $orderInfo;
            }
            if(!empty($vo['product_id']) && $vo['order_type'] == 0){
                $productData = [];
                $product = json_decode($vo['product_id'], true);
                if(is_array($product)){
                    foreach ($product as $productId => $attr){
                        $productData[$productId]['attr'] = $attr;
                        $productData[$productId]['name'] = db('store_goods')->where(['id' => $productId])->value('title');
                    }
                    $vo['productData'] = $productData;
                }
            }
            if(!empty($vo['envelope_id'])){
                $couponsId = db($this->couponsRecordTable)->where('id', $vo['envelope_id'])->value('coupons_id');
                $couponsInfo = db($this->couponsTable)->where('id', $couponsId)->field('id,coupons_code,name')->find();
//                $couponsInfo['record_id'] = $couponsId;
                $vo['couponsInfo'] = $couponsInfo;
            }
        }

    }

    public function del()
    {
        $this->applyCsrfToken();
        $this->_delete($this->table);
    }

    public function showDetail()
    {
        $id = $this->request->param('id');
        $userInfo = db($this->orderInfoTable)->where('id', $id)->find();
        $sex = ['女', '男'];
        $is_doing = ['否', '是'];
        $userInfo['sex'] = $sex[$userInfo['sex']];
        $userInfo['is_doing'] = $is_doing[$userInfo['is_doing']];
        $this->assign('vo', $userInfo);
        return $this->fetch('detail',['vo' => $userInfo]);
    }

    public function checkOrder()
    {
        $id = $this->request->param('id');
        // 启动事务
        Db::startTrans();
        $res = Db::table($this->table)->where('id', $id)->update(['status' => 4]);
        if($id){
            //发送订阅消息
            $activityData =  Db::table($this->table)->where('id', $id)->column('id,activity_id,user_id, pay_at, form_id', 'id');
            $liteApp = new LiteApp(config('wechat.miniapp'));
            $sendData = Db::table($this->activityTable)->field('name')->where('id', $activityData[$id]['activity_id'])->find();
            $sendData['res'] = '审核通过';
            $sendData['pay_at'] = $activityData[$id]['pay_at'];
            try {
                $liteApp->subscribeMessageSend($activityData[$id]['user_id'], $sendData);
            } catch (InvalidResponseException $e) {
                // 回滚事务
                Db::rollback();
                $this->error('(1)用户拒绝接受订阅消息！', $res);
            } catch (LocalCacheException $e) {
                // 回滚事务
                Db::rollback();
                $this->error('(2)用户拒绝接受订阅消息！', $res);
            }
            // 提交事务
            Db::commit();
//            $res['sendRes'] = isset($sendRes) ? $sendRes:'';
            $this->success('操作成功！', $res);
        }else{
            $this->error('操作失败！', $res);
        }
    }

    public function checkOrderRefuse()
    {
        $id = $this->request->param('id');
        // 启动事务
        Db::startTrans();
        $res = Db::table($this->table)->where('id', $id)->update(['status' => 5]);
        $order =  Db::table($this->table)->where('id', $id)->find();
        //退款
        try {
//            var_dump([
//                'transaction_id' => $order['pay_no'],
//                'out_refund_no'  => $this->createOrderSn($order['activity_id'], $order['group_id']),
//                'total_fee'      => $order['price'] * 100,
//                'refund_fee'     => $order['pay_price'] * 100,
//                'refund_account' => 'REFUND_SOURCE_UNSETTLED_FUNDS',
//            ]);exit;
            $model = new Refund(config('wechat.miniapp'));

            $result = $model->create([
                'transaction_id' => $order['pay_no'],
                'out_refund_no'  => $this->createOrderSn($order['activity_id'], $order['group_id']),
                'total_fee'      => $order['price'] * 100,
                'refund_fee'     => $order['pay_price'] * 100,
//                'refund_account' => 'REFUND_SOURCE_UNSETTLED_FUNDS',
            ]);
            if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
                Db::name('lite_order')->where(['order_sn' => $order['order_sn']])->update([
                    'refund_state' => '2', 'refund_desc' => '退款成功！',
                ]);
            } else {
                Db::name('lite_order')->where(['order_sn' => $order['order_sn']])->update([
                    'refund_desc' => isset($result['err_code_des']) ? $result['err_code_des'] : '退款失败',
                ]);
            }
        } catch (\WeChat\Exceptions\LocalCacheException $e) {
//            $this->output->writeln("订单 {$order['order_no']} 执行退款失败，{$e->getMessage()}！");
//            Db::name('StoreOrder')->where(['order_no' => $order['order_no']])->update(['refund_desc' => $e->getMessage()]);
            Db::rollback();
            $this->error('退款失败！', $e);
        }
        if($id){
            //发送订阅消息
            $activityData =  Db::table($this->table)->where('id', $id)->column('id,activity_id,user_id, pay_at', 'id');
            $liteApp = new LiteApp(config('wechat.miniapp'));
            $sendData = Db::table($this->activityTable)->field('name')->where('id', $activityData[$id]['activity_id'])->find();
            $sendData['res'] = '审核未通过';
            $sendData['pay_at'] = $activityData[$id]['pay_at'];
            $sendData['refuseData'] = $this->request->param('msg');
            try {
                $liteApp->subscribeMessageSend($activityData[$id]['user_id'], $sendData);
            } catch (InvalidResponseException $e) {
                // 回滚事务
                Db::rollback();
                $this->error('(1)用户拒绝接受订阅消息！', $res);
            } catch (LocalCacheException $e) {
                // 回滚事务
                Db::rollback();
                $this->error('(2)用户拒绝接受订阅消息！', $res);
            }
            // 提交事务
            Db::commit();
//            $res['sendRes'] = isset($sendRes) ? $sendRes:'';
            $this->success('操作成功！', $res);
        }else{
            $this->error('操作失败！', $res);
        }
    }

    private function createOrderSn($id = 0, $group_id = 0){
        return  date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$id.$group_id;
    }

    public function showAddress()
    {
        $id = $this->request->param('id');
        $data = db('store_member_address')->where(['id' => $id])->find();
        $this->assign('vo', $data);
        return $this->fetch('address',['vo' => $data]);
    }

}